# coding=utf-8
"""
author: jamon
"""
import asyncio
import threading
from asyncio import AbstractEventLoop
from typing import Optional, List, Dict

from openpyxl.compat.singleton import Singleton

from client.model.user_profile import UserProfile


class GlobalData(object, metaclass=Singleton):
    """全局数据"""

    def __init__(self):
        self.user_id: Optional[int] = None
        self.user_name: str = ""
        self.password: str = ""
        self.is_login: bool = False

        self.passed_gate_id = 0

        self.team_users: List[UserProfile] = []

        self.loop: Optional[AbstractEventLoop] = None

    def cache_login_info(self, user_name: str, password: str) -> None:
        self.user_name = user_name
        self.password = password

    def set_team_users(self, user_infos: List[Dict]):
        self.team_users = []
        for info in user_infos:
            user_profile = UserProfile(info["user_id"], info["user_name"])
            self.team_users.append(user_profile)

    def start_loop(self, loop):
        self.loop = loop
        asyncio.set_event_loop(self.loop)
        self.loop.run_forever()

    def run_loop(self):
        # 在当前线程下创建时间循环，（未启用），在start_loop里面启动它
        new_loop = asyncio.new_event_loop()
        # 通过当前线程开启新的线程去启动事件循环
        t = threading.Thread(target=self.start_loop, args=(new_loop,))
        t.start()
